package com.study.linkedlist;

/**
 * 删除链表中等于给定值 val 的所有节点。
 * 输入: 1->2->6->3->4->5->6, val = 6
 * 输出: 1->2->3->4->5
 */
public class LeetCode203 {

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }

        // 链表节点的构造函数
        // 使用arr为参数，创建一个链表，当前的ListNode为链表头节点
        public ListNode(int[] arr) {

            if (arr == null || arr.length == 0)
                throw new IllegalArgumentException("arr cannot be empty.");
            this.val = arr[0];
            ListNode cur = this;
            for (int i = 1; i < arr.length; i++) {
                cur.next = new ListNode(arr[i]);
                cur = cur.next;
            }

        }

        // 以当前节点为头节点的链表信息字符串
        @Override
        public String toString() {
            StringBuilder res = new StringBuilder();
            ListNode cur = this;
            while (cur != null) {
                res.append(cur.val + "->");
                cur = cur.next;
            }
            res.append("NULL");
            return res.toString();
        }
    }

    public static void main(String[] args) {
        int arr[] = {1, 2, 3, 4, 6, 5, 6, 7};
        ListNode listNode = new ListNode(arr);
        System.out.println(listNode);
        System.out.println(new LeetCode203().removeElements(listNode, 6));
        System.out.println(new LeetCode203().removeElements2(listNode, 6));
    }

    public ListNode removeElements(ListNode head, int val) {

        while (head != null && head.val == val) {
            ListNode delNode = head;
            head = head.next;
            delNode.next = null;
        }

        if (head == null)
            return null;

        ListNode prev = head;
        while (prev.next != null) {
            if (prev.next.val == val) {
                ListNode delNode = prev.next;
                prev.next = delNode.next;
                delNode.next = null;
            } else {
                prev = prev.next;
            }
        }
        return head;
    }

    public ListNode removeElements2(ListNode head, int val) {

        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;

        ListNode prev = dummyHead;
        while (prev.next != null) {
            if (prev.next.val == val) {
                ListNode delNode = prev.next;
                prev.next = delNode.next;
                delNode.next = null;
            } else {
                prev = prev.next;
            }
        }
        return dummyHead.next;
    }
}
